package com.sl.biz.modular.restapi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sl.biz.modular.ai.controller.domain.request.AiGenerateEntityRequest;
import com.sl.biz.modular.ai.service.AiChatRunBizService;
import com.sl.biz.modular.restapi.controller.request.ApiConfigQueryByIdRequest;
import com.sl.biz.modular.restapi.controller.request.ApiConfigQueryByIdsRequest;
import com.sl.biz.modular.restapi.controller.request.ApiConfigUpdateByIdRequest;
import com.sl.biz.modular.restapi.controller.request.ApiVersionConfigUpdateByIdRequest;
import com.sl.biz.modular.restapi.controller.response.ApiConfigQueryByIdVO;
import com.sl.biz.modular.restapi.controller.response.ApiVersionConfigQueryByApiIdVO;
import com.sl.biz.modular.restapi.dao.entity.ApiConfigDO;
import com.sl.biz.modular.restapi.dao.entity.ApiEntityConfigDO;
import com.sl.biz.modular.restapi.dao.entity.ApiHeaderConfigDO;
import com.sl.biz.modular.restapi.dao.entity.ApiVersionConfigDO;
import com.sl.biz.modular.restapi.dao.enums.ApiStatusCodeEnum;
import com.sl.biz.modular.restapi.dao.service.ApiConfigDaoService;
import com.sl.biz.modular.restapi.dao.service.ApiEntityConfigDaoService;
import com.sl.biz.modular.restapi.dao.service.ApiHeaderConfigDaoService;
import com.sl.biz.modular.restapi.dao.service.ApiVersionConfigDaoService;
import com.sl.biz.modular.restapi.service.ApiConfigBizService;
import com.sl.common.pojo.CommonEntity;
import com.sl.core.engine.exchange.CamelConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public  class ApiConfigBizServiceImpl implements ApiConfigBizService {

    private final ApiConfigDaoService apiConfigDaoService;

    private final ApiHeaderConfigDaoService headerConfigDaoService;

    private final ApiEntityConfigDaoService entityConfigDaoService;


    private final ApiVersionConfigDaoService versionConfigDaoService;
    private final AiChatRunBizService aiChatRunBizService;

    @Override
    public String save(ApiConfigDO apiConfigDO) {
        String apiStatusCode = apiConfigDO.getApiStatusCode();
        if (StrUtil.isBlank(apiStatusCode)) {
            apiConfigDO.setApiStatusCode(ApiStatusCodeEnum.OFFLINE.getCode());
        }
        apiConfigDaoService.saveOrUpdate(apiConfigDO);
        return apiConfigDO.getId();
    }

    @Override
    public List<ApiConfigDO> list(ApiConfigDO apiConfigDO) {
        LambdaQueryWrapper<ApiConfigDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(apiConfigDO.getGroupId()),
                ApiConfigDO::getGroupId, apiConfigDO.getGroupId());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(apiConfigDO.getProductId()),
                ApiConfigDO::getProductId, apiConfigDO.getProductId());
        lambdaQueryWrapper.eq(StrUtil.isNotBlank(apiConfigDO.getApiStatusCode()),
                ApiConfigDO::getApiStatusCode, apiConfigDO.getApiStatusCode());
        return apiConfigDaoService.list(lambdaQueryWrapper);
    }

    @Override
    public Boolean updateById(ApiConfigUpdateByIdRequest apiConfigUpdateByIdRequest) {

        String host = apiConfigUpdateByIdRequest.getHost();
        if (StrUtil.isNotBlank(host)) {
            apiConfigUpdateByIdRequest.setThirdApiFlag(true);
        } else {
            apiConfigUpdateByIdRequest.setThirdApiFlag(false);
        }
        String apiId = apiConfigUpdateByIdRequest.getId();
        //先修改自身
        apiConfigDaoService.updateById(apiConfigUpdateByIdRequest);


        List<ApiVersionConfigUpdateByIdRequest> versionList = apiConfigUpdateByIdRequest.getVersionList();

        versionConfigDaoService.removeByApiId(apiId);

        for (ApiVersionConfigUpdateByIdRequest apiVersionConfigUpdateByIdRequest : versionList) {
            apiVersionConfigUpdateByIdRequest.setApiId(apiId);
            String apiVersionId = apiVersionConfigUpdateByIdRequest.getId();
            if (StrUtil.isNotBlank(apiVersionId)) {
                headerConfigDaoService.removeByApiVersionConfigId(apiVersionId);
                entityConfigDaoService.removeByApiVersionConfigId(apiVersionId);
            }

            apiVersionConfigUpdateByIdRequest.setId(null);

            //先修改自身
            versionConfigDaoService.save(apiVersionConfigUpdateByIdRequest);

            String id = apiVersionConfigUpdateByIdRequest.getId();
            //

            List<ApiHeaderConfigDO> headers = apiVersionConfigUpdateByIdRequest.getHeaders();

            if (CollUtil.isNotEmpty(headers)) {
                headers.forEach(v -> {
                    v.setApiId(apiId);
                    v.setApiVersionId(id);
                    v.setId(null);
                });
                headerConfigDaoService.saveBatch(headers);
            }


            ApiEntityConfigDO entity = apiVersionConfigUpdateByIdRequest.getEntity();
            entity.setApiId(apiId);
            entity.setApiVersionId(id);
            entity.setId(null);
            entityConfigDaoService.save(entity);
        }

        changeApi(apiId);
        return Boolean.TRUE;
    }

    private void changeApi(String apiId) {
        ApiConfigDO byId = apiConfigDaoService.getById(apiId);
        if (ObjectUtil.isNull(byId)) {
            return;
        }

        //需要对这个ID进行处理，如果没有则要删除，如果有则要新增
        Boolean thirdApiFlag = byId.getThirdApiFlag();
        if (BooleanUtil.isTrue(thirdApiFlag)) {
            CamelConfig.INSTANCE.removeApi(apiId);
            return;
        }
        String apiStatusCode = byId.getApiStatusCode();
        if (StrUtil.equals(apiStatusCode, ApiStatusCodeEnum.OFFLINE.getCode())) {
            CamelConfig.INSTANCE.removeApi(apiId);
        } else {
            CamelConfig.INSTANCE.changeApi(apiId);
        }
    }

    @Override
    public ApiConfigQueryByIdVO queryById(ApiConfigQueryByIdRequest apiConfigUpdateByIdRequest) {

        String id = apiConfigUpdateByIdRequest.getId();

        ApiConfigDO byId = apiConfigDaoService.getById(id);
        if(ObjectUtil.isNull(byId)){
            return null;
        }
        ApiConfigQueryByIdVO apiConfigQueryByIdVO = BeanUtil.copyProperties(byId, ApiConfigQueryByIdVO.class);

        List<ApiVersionConfigQueryByApiIdVO> apiVersionConfigQueryByApiIdVOS = this.queryVersionByApiId(apiConfigUpdateByIdRequest);
        apiConfigQueryByIdVO.setVersionList(apiVersionConfigQueryByApiIdVOS);
        return apiConfigQueryByIdVO;
    }

    @Override
    public List<ApiVersionConfigQueryByApiIdVO> queryVersionByApiId(ApiConfigQueryByIdRequest apiConfigUpdateByIdRequest) {

        List<ApiVersionConfigDO> apiVersionConfigDOS = versionConfigDaoService.queryByApiConfigId(apiConfigUpdateByIdRequest.getId());

        if (CollUtil.isEmpty(apiVersionConfigDOS)) {
            return Collections.emptyList();
        }
        List<ApiVersionConfigQueryByApiIdVO> result = BeanUtil.copyToList(apiVersionConfigDOS, ApiVersionConfigQueryByApiIdVO.class);
        List<String> versionIdList = apiVersionConfigDOS.stream().map(CommonEntity::getId).distinct().collect(Collectors.toList());


        //在查询header
        List<ApiHeaderConfigDO> apiHeaderConfigDOS = headerConfigDaoService.queryByVersionIdList(versionIdList);
        Map<String, List<ApiHeaderConfigDO>> headerGroupMap = apiHeaderConfigDOS.stream().collect(Collectors.groupingBy(v -> v.getApiVersionId()));

//        apiConfigQueryByIdVO.setHeaders(apiHeaderConfigDOS);

        List<ApiEntityConfigDO> apiEntityConfigDO = entityConfigDaoService.queryByVersionIdList(versionIdList);
        Map<String, ApiEntityConfigDO> entityGroupMap = apiEntityConfigDO.stream().collect(Collectors.toMap(v -> v.getApiVersionId(), Function.identity(), (k1, k2) -> k1));

        for (ApiVersionConfigQueryByApiIdVO apiVersionConfigQueryByApiIdVO : result) {

            List<ApiHeaderConfigDO> apiHeaderConfigDOS1 = headerGroupMap.get(apiVersionConfigQueryByApiIdVO.getId());
            apiVersionConfigQueryByApiIdVO.setHeaders(apiHeaderConfigDOS1);

            ApiEntityConfigDO entityConfigDO = entityGroupMap.get(apiVersionConfigQueryByApiIdVO.getId());
            apiVersionConfigQueryByApiIdVO.setEntity(entityConfigDO);
        }
        return result;
    }

    @Override
    public List<ApiVersionConfigQueryByApiIdVO> queryVersionByApiIds(ApiConfigQueryByIdsRequest apiConfigUpdateByIdRequest) {
        List<String> ids = apiConfigUpdateByIdRequest.getIds();
        if(CollUtil.isEmpty(ids)){
            return Collections.emptyList();
        }
        List<ApiVersionConfigDO> apiVersionConfigDOS = versionConfigDaoService.queryByApiConfigIds(apiConfigUpdateByIdRequest.getIds());

        if (CollUtil.isEmpty(apiVersionConfigDOS)) {
            return Collections.emptyList();
        }
        List<ApiVersionConfigQueryByApiIdVO> result = BeanUtil.copyToList(apiVersionConfigDOS, ApiVersionConfigQueryByApiIdVO.class);
        List<String> versionIdList = apiVersionConfigDOS.stream().map(CommonEntity::getId).distinct().collect(Collectors.toList());


        //在查询header
        List<ApiHeaderConfigDO> apiHeaderConfigDOS = headerConfigDaoService.queryByVersionIdList(versionIdList);
        Map<String, List<ApiHeaderConfigDO>> headerGroupMap = apiHeaderConfigDOS.stream().collect(Collectors.groupingBy(v -> v.getApiVersionId()));

//        apiConfigQueryByIdVO.setHeaders(apiHeaderConfigDOS);

        List<ApiEntityConfigDO> apiEntityConfigDO = entityConfigDaoService.queryByVersionIdList(versionIdList);
        Map<String, ApiEntityConfigDO> entityGroupMap = apiEntityConfigDO.stream().collect(Collectors.toMap(v -> v.getApiVersionId(), Function.identity(), (k1, k2) -> k1));

        for (ApiVersionConfigQueryByApiIdVO apiVersionConfigQueryByApiIdVO : result) {

            List<ApiHeaderConfigDO> apiHeaderConfigDOS1 = headerGroupMap.get(apiVersionConfigQueryByApiIdVO.getId());
            apiVersionConfigQueryByApiIdVO.setHeaders(apiHeaderConfigDOS1);

            ApiEntityConfigDO entityConfigDO = entityGroupMap.get(apiVersionConfigQueryByApiIdVO.getId());
            apiVersionConfigQueryByApiIdVO.setEntity(entityConfigDO);
        }
        return result;
    }

    @Override
    public Boolean setApiStatusCode(ApiConfigDO apiConfigDO) {
        Boolean b = apiConfigDaoService.setApiStatusCode(apiConfigDO.getId(),
                apiConfigDO.getApiStatusCode());
        changeApi(apiConfigDO.getId());
        return b;
    }

    @Override
    public Boolean versionSetLatestFlag(ApiVersionConfigDO apiVersionConfigDO) {
        //先删除其他版本的
        ApiVersionConfigDO byId = versionConfigDaoService.getById(apiVersionConfigDO.getId());
        if (ObjectUtil.isNull(byId)) {
            return Boolean.FALSE;
        }

        versionConfigDaoService.setLatestFlagByApiId(
                byId.getApiId(), false
        );

        return versionConfigDaoService.setLatestFlag(apiVersionConfigDO.getId(),
                apiVersionConfigDO.getLatestFlag());
    }

    @Override
    public Boolean removeById(ApiConfigDO apiConfigDO) {

        String apiId = apiConfigDO.getId();
        //先修改自身
        apiConfigDaoService.removeById(apiConfigDO);

        List<ApiVersionConfigDO> versionList = versionConfigDaoService.queryByApiConfigId(apiId);

        versionConfigDaoService.removeByApiId(apiId);

        for (ApiVersionConfigDO apiVersionConfigDO : versionList) {
            apiVersionConfigDO.setApiId(apiId);
            String apiVersionId = apiVersionConfigDO.getId();
            headerConfigDaoService.removeByApiVersionConfigId(apiVersionId);
            entityConfigDaoService.removeByApiVersionConfigId(apiVersionId);
        }

        CamelConfig.INSTANCE.removeApi(apiId);
        return Boolean.TRUE;
    }

    @Override
    public ApiVersionConfigQueryByApiIdVO aiGenerateProcessFile(AiGenerateEntityRequest aiGenerateEntityRequest) {
        aiGenerateEntityRequest.setPrefixKeywords("我有一个流程驱动框架.我现在需要创建接口定义,接口定义里面的inputParam和resultParam字段定义是这样的[{\n" +
                "  \"fieldCode\": \"fieldCode_9edb7a05303f\",\n" +
                "  \"fieldName\": \"fieldName_bc01ac9d3242\",\n" +
                "  \"fieldType\": \"fieldType_6b6f482fd3a7\",\n" +
                "  \"fieldDesc\": \"fieldDesc_1ef823be8c71\",\n" +
                "  \"isArrayFlag\": false,\n" +
                "  \"remark\": \"remark_f3a245008938\",\n" +
                "  \"sort\": 0,\n" +
                "  \"path\": \"path_8d156f1019fe\",\n" +
                "  \"defaultValue\": \"defaultValue_02180461a8b3\",\n" +
                "  \"children\": [\n" +
                "    {}\n" +
                "  ]\n" +
                "}]下面是我对你需要帮我创建API的描述。");
        ApiVersionConfigQueryByApiIdVO  squareLakeLayout = aiChatRunBizService.execute(aiGenerateEntityRequest, ApiVersionConfigQueryByApiIdVO.class);
        return squareLakeLayout;
    }
}
